/*  File Name	: DBMonitor.h
 *  Author		: Pang Jiacai
 *	 E-mail		: 823960168@qq.com
 *  Created on	: 2012-11-30
 *  Description:
 */

#ifndef DBMONITOR_H_
#define DBMONITOR_H_
#include "Monitor.h"
#include "MonitorSock.h"
#include "DBService.h"
#include "Configurator.h"

class PlayerBaseInfo;

class MySqlDB;

struct ServerInfo
{
	ServerInfo()
	{
		reset();
	}
	void reset(void)
	{
		server_id=0;
		svc_id = 0;
	}
	int server_id;
	int svc_id;
};

struct DBPlayer:public PlayerBaseInfo
{
	DBPlayer()
	{
		dbport = 0;
		is_login = false;
		dbip = "";
		pwd_ = "";
	}
	bool is_login;
	int dbport;
	std::string pwd_;
	std::string dbip;
};

typedef std::map<std::string,DBPlayer> AccountMap;

class DBMonitor:public Monitor<DBService>
{
public:
	typedef Monitor<DBService> super;
	typedef MonitorAcceptor<DBMonitor,DBService> DBServerAcceptor;
	typedef std::map<int,ServerInfo*> ServerMap;
	typedef std::map<std::string,MySqlDB*> DBMap;


	virtual ~DBMonitor();

	static DBMonitor *instance(void);

	virtual int init(int line_id,int list_size=10240,int block_size=4096,int pool_size=10240,
			int growth_size=1024,std::string pool_name="DBMonitor-Msg");
	virtual int start(void);
	virtual int stop(void);

	virtual int run_request_loop(void);
	virtual int run_respond_loop(void);
	void collection_info(void);

	const Json::Value &cfg(void);

	int respond_succ_to_client(int id,int cmd,MessageBlock *mb=NULL);
	int respond_error_to_client(int id,int cmd,int error,MessageBlock *mb=NULL);

	std::string db_key(std::string ip,int port);
	MySqlDB *local_db(void);
	MySqlDB *find_db(std::string ip,int port);

private:
	DBMonitor();

	int process_request(MessageBlock *mb);
	int process_respond(MessageBlock *mb);

	int web_create_account(int svc_id,MessageBlock *mb);
	int web_login(int svc_id,MessageBlock *mb);
	int web_logout(int svc_id,MessageBlock *mb);
	int player_login(int svc_id,MessageBlock *mb);

	int load_account(AccountMap &map);

	int init_db(void);
	int assign_db(DBPlayer &player);

private:
	static DBMonitor* instance_;
	DBServerAcceptor *acceptor_;
	ServerMap server_map_;

	bool load_succ_;
	AccountMap account_map_;
	DBMap db_map_;

	RT_MUTEX rt_mutex_;
	RT_MUTEX account_mutex_;
};

#endif /* DBMONITOR_H_ */
